//
//  AYuStatusViewModel.swift
//  SHWeibo3
//
//  Created by 余伟康 on 16/7/23.
//  Copyright © 2016年 wangce. All rights reserved.
//

import UIKit

class AYuStatusViewModel: NSObject {

    // 定义一个属性
    var status : AYuStatus?
    
    // 微博认证图片
    var avatarImage:UIImage?
    
    // 处理会员等级图片
    var memberImage:UIImage?
    
    // 微博来源处理富文本
    var sourceAttr:NSMutableAttributedString?
    
    // 微博时间
    var sinaTimeStr:String?{
        return NSDate.sinaDate(status?.created_at ?? "")?.sinaDescripitionStr
    }
    
    // 重载构造函数
    init(status:AYuStatus) {
        super.init()
        self.status = status
        
        self.avatarImage = getAvatarImage(status.user?.verified)
        self.memberImage = getMemberImage(status.user?.mbrank)
        self.sourceAttr = getSourceStr(status.source)
    }
    
    
}

// MARK: - 数据处理

extension AYuStatusViewModel{
    func getAvatarImage(verified:Int?)->UIImage?{
        // 判断是否为nil
        guard let ver = verified else{
            return nil
        }
        
        switch ver {
        case 1:
            return UIImage(named: "avatar_vip")
        case 2,3,5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return UIImage(named: "avatar_vgirl")
        }
    }
    
    
    func getMemberImage(mbrank:Int?)->UIImage?{
        guard let mbr = mbrank else{
            return nil
        }
        if mbr > 0 && mbr < 7 {
            return UIImage(named: "common_icon_membership_level\(mbr)")
        }
        return UIImage(named: "common_icon_membership")
    }
}

// MARK: - 微博来源数据处理 -显示最终数据
extension AYuStatusViewModel{

    func getSourceStr(suorce:String?)->NSMutableAttributedString{
        // 判断是否 为nil 且是否有"\>"
        guard let s = suorce where s.containsString("\">") else{
            let str = "上海三期微博"
            return getSourceAttr(str)
        }
        // 起始位置 和 结束位置
        let startRange = s.rangeOfString("\">")!
        let endRange = s.rangeOfString("</")!
        
        //字符串截取
        let result = s.substringWithRange(startRange.endIndex..<endRange.startIndex)
        return getSourceAttr(result)

    }
    // 处理显示微博来源的富文本
    func getSourceAttr(result:String)->NSMutableAttributedString{
        // 最终显示格式
        let name = "来自 " + result
        // 得到range
        let range = (name as NSString).rangeOfString("来自")
        
        // 创建一个可变富文本
        let attr = NSMutableAttributedString(string: name)
        // 设置属性
        attr.addAttributes([NSForegroundColorAttributeName : UIColor.grayColor()], range: range)
        
        return attr
    }
}










